/**
 * Copyright 2010 VTT Finnish Technical Research Centre
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.osami.syncagent.impl;

import java.lang.reflect.Array;
import java.net.URI;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.osami.syncagent.SyncAgentService;
import org.osgi.service.event.Event;


public class SyncAgentServiceImpl implements SyncAgentService {
		private Activator agent;
		private String ID;
		
		public SyncAgentServiceImpl(String iD)
		{
			ID = iD;
		}
		public void setActivatorRef(Activator syncAgent) {
			agent = syncAgent;
		}

		public String sayHello() {
			return "Hello World!! ";
		}

		public String sayGoodbye() {
			return "Goodbye World!!";
		}

		public void callHome(URI homeAddress) {
			// TODO Auto-generated method stub
			
		}

		public void pushEvents(Event events) {
			/*
			String[] params = events.getPropertyNames();
			Dictionary result = new Hashtable();  
			
			for(int i = 0; i < params.length; i++)
			{
				result.put(params[i], events.getProperty(params[i]));  
			}
			//RemoteEvent pEvent = new RemoteEvent(events.getTopic(), result);
			*/
			String message;
			message = "topic="+events.getTopic()+",";
			String[] params = events.getPropertyNames();
			for(int i = 0; i < params.length; i++)
			{
				if (i == params.length-1)
				{
					message += params[i]+"="+events.getProperty(params[i]);
				}
				else 
				{
					message += params[i]+"="+events.getProperty(params[i])+",";  
				}
			}
			
			// push events to remote OSGi clients
			Map<SyncAgentService, String> agents = agent.getClients();
			
			for (Iterator<Entry<SyncAgentService, String>> it = agents.entrySet().iterator(); it.hasNext(); ) {
                Entry<SyncAgentService, String> entry = it.next();
                try {
                	System.out.println("Sending an event to remote agent");
                    entry.getKey().publishEvents(message);//pEvent);
                } catch (Throwable th) {
                    System.out.println("Could not send message to agent: " + entry.getValue());
                    System.out.println("message was: " + th.getMessage());
                }
            }
			System.out.println("pushing to non OSGi 4.2 clients");
			// then push the events to other clients
			agent.pushToClients(message);
			
		}

		public String getID() {
			return ID;
		}

		public void publishEvents(String event) {
			System.out.println("Received an event! : " + event);
			Event nEvent = new Event(parseTopic(event), parseProperties(event));
		
			publishEvents(nEvent);
		}

		private Dictionary parseProperties(String event) {
			Dictionary result = new Hashtable();  
			String []props = event.split(",");
			result.put("remote", "1");
			for (int i = 1; i < Array.getLength(props);i++)
			{
				String[] keyValuePair = props[i].split("=");
				result.put(keyValuePair[0],keyValuePair.length>1?keyValuePair[1]:"");  
			}
			return result;
		}
		private String parseTopic(String event) {
			String []topics = event.split(",");
			String topic = topics[0].split("=")[1];
			System.out.println("parseTopic: setting Topic to \""+topic+"\"");
			return topic;
		}
		
		public void publishEvents(Event event) {
			System.out.println("Posting an event localy!");			
			if(agent==null) {
				System.out.println("agent = null!");
				return;
			} else
			if(agent.getEventAdmin() == null) {
				System.out.println("agent.getEventAdmin() = null!");
				return;
			}
			agent.getEventAdmin().postEvent(event);						
		}
}
